/**
 * React Native 日志打印系统
 * 支持远程日志发送和本地日志管理
 */

import { Platform } from 'react-native'

class Logger {
  constructor(config = {}) {
    this.config = {
      serverUrl: config.serverUrl || 'http://192.168.1.100:3000',
      enableRemoteLogging: config.enableRemoteLogging !== false,
      enableConsoleLogging: config.enableConsoleLogging !== false,
      maxLocalLogs: config.maxLocalLogs || 1000,
      autoSendInterval: config.autoSendInterval || 0, // 0 表示立即发送
      ...config,
    }

    this.localLogs = []
    this.isConnected = false
    this.sendQueue = []
    this.isOnline = true

    // 检测网络状态
    this._setupNetworkListener()

    // 自动发送队列中的日志
    if (this.config.autoSendInterval > 0) {
      this._setupAutoSend()
    }
  }

  /**
   * 设置网络监听
   */
  _setupNetworkListener() {
    try {
      const NetInfo = require('@react-native-community/netinfo')
      NetInfo.addEventListener((state) => {
        this.isOnline = state.isConnected
        if (this.isOnline && this.sendQueue.length > 0) {
          this._processSendQueue()
        }
      })
    } catch (error) {
      // NetInfo 不可用时的降级处理
      console.warn('NetInfo not available, assuming online status')
    }
  }

  /**
   * 设置自动发送
   */
  _setupAutoSend() {
    setInterval(() => {
      if (this.sendQueue.length > 0) {
        this._processSendQueue()
      }
    }, this.config.autoSendInterval)
  }

  /**
   * 处理发送队列
   */
  async _processSendQueue() {
    if (!this.isOnline || this.sendQueue.length === 0) return

    const batch = [...this.sendQueue]
    this.sendQueue = []

    try {
      await Promise.all(batch.map((logData) => this._sendToServer(logData)))
    } catch (error) {
      // 发送失败，重新加入队列
      this.sendQueue.unshift(...batch)
      console.warn('Failed to send log batch:', error.message)
    }
  }

  /**
   * 发送日志到服务器
   */
  async _sendToServer(logData) {
    if (!this.config.enableRemoteLogging) return

    try {
      const response = await fetch(`${this.config.serverUrl}/api/log`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(logData),
        timeout: 5000, // 5秒超时
      })

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`)
      }

      this.isConnected = true
      return response.json()
    } catch (error) {
      this.isConnected = false

      // 如果是离线或网络错误，加入发送队列
      if (this.config.autoSendInterval > 0) {
        this.sendQueue.push(logData)
      }

      throw error
    }
  }

  /**
   * 格式化日志消息
   */
  _formatMessage(level, messages) {
    const timestamp = new Date().toISOString()
    const platformInfo = Platform.OS === 'ios' ? 'iOS' : 'Android'

    return {
      timestamp: Date.now().toString(),
      level,
      platform: platformInfo,
      message: messages.map((msg) => {
        if (typeof msg === 'object') {
          try {
            return JSON.stringify(msg, null, 2)
          } catch (e) {
            return String(msg)
          }
        }
        return String(msg)
      }),
    }
  }

  /**
   * 存储本地日志
   */
  _storeLocalLog(logData) {
    this.localLogs.push(logData)

    // 限制本地日志数量
    if (this.localLogs.length > this.config.maxLocalLogs) {
      this.localLogs = this.localLogs.slice(-this.config.maxLocalLogs)
    }
  }

  /**
   * 通用日志方法
   */
  async _log(level, ...messages) {
    const logData = this._formatMessage(level, messages)

    // 存储本地日志
    this._storeLocalLog(logData)

    // 控制台输出
    if (this.config.enableConsoleLogging) {
      const consoleMethod = console[level] || console.log
      consoleMethod(`[${level.toUpperCase()}]`, ...messages)
    }

    // 远程发送
    if (this.config.enableRemoteLogging) {
      if (this.config.autoSendInterval > 0) {
        this.sendQueue.push(logData)
      } else {
        try {
          await this._sendToServer(logData)
        } catch (error) {
          // 静默处理发送错误
        }
      }
    }

    return logData
  }

  // 日志级别方法
  debug(...messages) {
    return this._log('debug', ...messages)
  }

  info(...messages) {
    return this._log('info', ...messages)
  }

  log(...messages) {
    return this._log('log', ...messages)
  }

  warn(...messages) {
    return this._log('warn', ...messages)
  }

  error(...messages) {
    return this._log('error', ...messages)
  }

  /**
   * 清空远程日志
   */
  async clear() {
    const clearData = this._formatMessage('clear', ['clear'])
    try {
      await this._sendToServer(clearData)
    } catch (error) {
      console.warn('Failed to clear remote logs:', error.message)
    }
  }

  /**
   * 清空本地日志
   */
  clearLocal() {
    this.localLogs = []
  }

  /**
   * 获取本地日志
   */
  getLocalLogs(level = null) {
    if (level) {
      return this.localLogs.filter((log) => log.level === level)
    }
    return [...this.localLogs]
  }

  /**
   * 获取连接状态
   */
  getConnectionStatus() {
    return {
      isConnected: this.isConnected,
      isOnline: this.isOnline,
      queueLength: this.sendQueue.length,
      localLogsCount: this.localLogs.length,
    }
  }

  /**
   * 更新配置
   */
  updateConfig(newConfig) {
    this.config = { ...this.config, ...newConfig }
  }

  /**
   * 手动触发发送队列
   */
  async flushQueue() {
    await this._processSendQueue()
  }
}

export default Logger


